package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.UserDto;
import com.itheima.reggie.pojo.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user) throws Exception {
        String phone = user.getPhone();
        String code = Integer.toString(ValidateCodeUtils.generateValidateCode(4));
//        session.setAttribute(phone, code);
        ValueOperations opsForValue = redisTemplate.opsForValue();
        opsForValue.set(phone,code,3, TimeUnit.MINUTES);

        return R.success(code);
    }

    @PostMapping("/login")
    public R login(@RequestBody UserDto userDto, HttpSession session) {
        String code = userDto.getCode();
        String phone = userDto.getPhone();
        User user = userService.getOne(new QueryWrapper<User>().eq("phone", phone));
        if (user == null) {
            userDto.setName("黑马学子");
            userDto.setStatus(1);
            userService.save(userDto);
        } else {
            userDto.setId(user.getId());
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String code1 = (String) valueOperations.get(phone);

        if (code.equals(code1)) {
            session.setAttribute("user", userDto);
            redisTemplate.delete(phone);
            return R.success("登,录成功");
        }
        return R.error("失败");
    }
    @PostMapping("/loginout")
    public R loginout(HttpSession session) {
        session.invalidate();
        return R.success("退出");
    }
}
